<template>
  <div class="sku-container">
    <div v-if="!props.disabled" class="sku-check">
      <div v-if="props.theme == 1" class="theme-1">
        <a-card v-for="(item, index) in data.myAttribute" :key="index" class="item" shadow="never">
          <template #title>
            <div>{{ item.name }}</div>
          </template>
          <a-checkbox v-for="(item2, index2) in item.item" :key="index2" v-model:checked="item2.checked">
            {{ item2.name }}
          </a-checkbox>
        </a-card>
      </div>
      <a-table v-else :dataSource="data.myAttribute" :show-header="false" class="theme-2">
        <a-table-column key="name" width="120" :resizable="false" />
      </a-table>
    </div>
    <div class="sku-list">
      <a-form ref="skuFormRef" :model="data.form" status-icon inline-message>
        <vxe-table
          v-if="emitAttribute?.length > 0"
          ref="skuTableRef"
          :border="false"
          max-height="500"
          :mouse-config="{ selected: true }"
          :keyboard-config="{ isEdit: true, isArrow: true, isEnter: true, isTab: true, isDel: true, isBack: true }"
          :edit-rules="validRules"
          :data="data.form.skuData"
          :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
        >
          <vxe-column type="seq" width="60" />
          <!--
            v-if和v-for联合使用规则:
            https://blog.csdn.net/cuclife/article/details/136076011
          -->
          <vxe-column
            v-for="(item, index) in props.structure"
            :key="`structure-${index}`"
            :field="item.name"
            :title="item.label"
            :visible="item.visible"
            :edit-render="item.onlyRead ? '' : { autofocus: '.vxe-input--inner', placeholder: '请点击输入' + item.label + '...' }"
          >
            <template #edit="{ row }">
              <vxe-input v-model="row[item?.name]" type="text" />
            </template>
          </vxe-column>
          <vxe-column title="操作" width="160">
            <template #default="{ row }">
              <vxe-button @click="removeRow(row)">删除</vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, watch, reactive, nextTick, onMounted, defineProps, defineEmits } from 'vue';
  import { VxeTablePropTypes } from 'vxe-table';
  import { removeById } from '/@/views/goods/sku/sku.api';
  const skuTableRef = ref();
  interface SkuType {
    sourceAttribute: any;

    attribute: any;

    sku: any;
    /**
     * 表格结构，注意name字段，用于输出sku数据
     */
    structure: any;
    // sku 字段分隔符
    separator: string;
    // 无规格的 sku
    emptySku: string;
    // 是否显示 sku 选择栏
    disabled: boolean;
    // 主题风格
    theme: number;
    // 是否开启异步加载
    async: boolean;
  }

  const props = withDefaults(defineProps<SkuType>(), {
    sourceAttribute: [] as any,
    attribute: [] as any,
    sku: [] as any,
    structure: [
      { name: 'id', type: 'normal', label: 'id', visible: false },
      { name: 'specName', label: '规格型号', onlyRead: true },
      { name: 'costPrice', type: 'input-number', label: '预计采购价' },
      { name: 'salePrice', type: 'input-number', label: '零售价' },
      { name: 'wholeSalePrice', type: 'input-number', label: '批发价' },
      { name: 'discountRate1', type: 'input-number', label: '折扣率一(%)' },
      { name: 'discountRate2', type: 'input-number', label: '折扣率二(%)' },
      { name: 'minStockNum', type: 'input-number', label: '最低库存' },
      { name: 'maxStockNum', type: 'input-number', label: '最高库存' },
    ] as any,
    separator: ';',
    emptySku: '',
    disabled: false,
    theme: 1,
    async: false,
  });

  const emits = defineEmits(['update:attribute', 'update:sku']);

  const data = reactive<any>({
    isInit: false,
    myAttribute: [],
    form: {
      skuData: [],
    },
    batch: {},
  });

  const skuFormRef = ref();

  const validRules = ref<VxeTablePropTypes.EditRules<any>>({
    salePrice: [{ required: true, message: '请输入零售价' }],
    totalNum: [{ required: true, message: '请输入库存' }],
  });
  const rules = computed(() => {
    // 重新生成验证规则
    let rules = {};
    props.structure.forEach((v) => {});
    return rules;
  });

  // 将 myAttribute 数据还原会 attribute 数据的结构，用于更新 attribute
  const emitAttribute = computed(() => {
    let attribute: any = [];
    data.myAttribute.forEach((v1) => {
      const obj: any = {
        name: v1.name,
        item: [],
      };
      v1.item.forEach((v2) => {
        if (v2.checked) {
          obj.item.push({
            specId: v2.specId,
            specName: v1.name + ':' + v2.name,
            name: v2.name,
          });
        }
      });
      if (obj.item.length !== 0) {
        attribute.push(obj);
      }
    });
    console.log('attribute', attribute);

    return attribute;
  });

  watch(
    () => props.sourceAttribute,
    () => {
      !props.async && init();
    },
    { deep: true }
  );
  watch(
    () => data.myAttribute,
    () => {
      if (!data.isInit) {
        // 更新父组件
        emits('update:attribute', emitAttribute.value);
      }
      // 解决通过 $emit 更新后无法拿到 attribute 最新数据的问题
      nextTick(() => {
        if (props.attribute.length !== 0) {
          // const specs = [
          //   {
          //     name: '硬盘容量',
          //     item: [
          //       { specId: '1811297303340048385', specName: '硬盘容量:256GB', name: '256GB' },
          //       { specId: '1811297303704952833', specName: '硬盘容量:512GB', name: '512GB' },
          //     ],
          //   },
          //   {
          //     name: '内存',
          //     item: [
          //       { specId: '1811297305068101633', specName: '内存:8G', name: '8G' },
          //       { specId: '1811297305407840258', specName: '内存:16G', name: '16G' },
          //     ],
          //   },
          //   {
          //     name: '颜色',
          //     item: [
          //       { specId: '1811297301490360322', specName: '颜色:红', name: '红' },
          //       { specId: '1811297301922373633', specName: '颜色:蓝', name: '蓝' },
          //     ],
          //   },
          // ];
          // const specs = [
          //   ['x', 'xl'],
          //   ['黑', '白', '灰'],
          //   ['绵', '涤纶'],
          //   ['170cm', '180cm'],
          // ];
          // const result = specs.reduce((rList, arr) => {
          //   arr.flatMap((it) => {
          //     console.log(rList);
          //     rList.map((r) => {
          //       console.log([...r, it]);
          //     });
          //     debugger;
          //   });
          // });
          // // const result = specs.reduce((rList, arr) => arr.flatMap((it) => rList.map((r) => [...r, it])), [[]]).map((it) => it.join('-'));
          // console.log(result);
          // // console.log(JSON.stringify(props.attribute));
          // const skuList = cartesian(specs);
          console.log('>>>:', props.attribute);
          console.log('>>>:', data.form.skuData);
          const result = cartesianAttribute(props.attribute);
          data.form.skuData = result;
          // combinationAttribute();
        } else {
          data.form.skuData = [];
          const obj = {
            sku: props.emptySku,
          };
          props.structure.forEach((v: any) => {
            // v.type == 'slot' &&
            if (!(v.skuProperty == false)) {
              obj[v.name] = typeof v.defaultValue != 'undefined' ? v.defaultValue : '';
            }
          });
          data.form.skuData.push(obj);
          console.log('skuData', obj);
        }
        clearValidate();
      });
    },
    { deep: true }
  );
  watch(
    () => data.form.skuData,
    (newValue, oldValue) => {
      if (!data.isInit || (newValue.length == 1 && newValue[0].sku == props.emptySku)) {
        // 如果有老数据，或者 sku 数据为空，则更新父级 sku 数据
        if (oldValue.length || !props.sku.length) {
          // 更新父组件
          const arr: any = [];
          newValue.forEach((v1) => {
            const obj: any = {
              sku: v1.sku,
            };
            props.structure.forEach((v2: any) => {
              if (!(v2.type == 'slot' && v2.skuProperty == false)) {
                obj[v2.name] = v1[v2.name] || (typeof v2.defaultValue != 'undefined' ? v2.defaultValue : '');
              }
            });
            if (obj.sku instanceof Array) {
              let specIds = obj.sku.map((o) => o.specId);
              let specNames = obj.sku.map((o) => o.specName);
              obj.specIds = specIds;
              obj.specNames = specNames;
            } else if (obj.sku instanceof Object) {
              obj.specIds = [obj.sku.specId];
              obj.specNames = [obj.sku.specName];
            }
            console.log('obj', obj);

            arr.push(obj);
          });
          // 使用map方法提取所有对象的id
          emits('update:sku', arr);
        }
      }
    },
    { deep: true }
  );
  onMounted(() => {
    !props.async && init();
  });
  //     methods: {
  function init() {
    nextTick(() => {
      data.isInit = true;
      // 初始化 myAttribute
      let myAttribute: any = [];
      // 根据 sourceAttribute 复原 myAttribute 的结构
      console.log('sourceAttribute', props.sourceAttribute);

      props.sourceAttribute.forEach((v: any) => {
        const temp: any = {
          name: v.name,
          canAddAttribute: typeof v.canAddAttribute != 'undefined' ? v.canAddAttribute : true,
          addAttribute: '',
          item: [],
        };

        v.children.forEach((c) => {
          temp.item.push({
            specId: c.id,
            name: c.name,
            checked: false,
          });
        });
        console.log(temp);

        myAttribute.push(temp);
      });

      // 根据 attribute 更新 myAttribute
      props.attribute.forEach((attrVal: any) => {
        myAttribute.forEach((myAttrVal: any) => {
          if (attrVal.name === myAttrVal.name) {
            attrVal.item.forEach((attrName) => {
              myAttrVal.item.some((myAttrItem) => {
                if (attrName.specId === myAttrItem.specId) {
                  myAttrItem.checked = true;
                }
                return attrName.name === myAttrItem.name;
              });
            });
          }
        });
      });
      data.myAttribute = myAttribute;
      // 通过 sku 更新 skuData，但因为 skuData 是实时监听 myAttribute 变化并自动生成，而 watch 是在 methods 后执行，所以增加 setTimeout 方法，确保 skuData 生成后在执行下面的代码
      setTimeout(() => {
        props.sku.forEach((skuItem: any) => {
          data.form.skuData.forEach((skuDataItem: any) => {
            if (skuItem.specName === skuDataItem.specName) {
              props.structure.forEach((structureItem: any) => {
                if (structureItem.name === 'specName') {
                  skuDataItem['specName'] = skuItem[structureItem.name];
                } else {
                  skuDataItem[structureItem.name] = skuItem[structureItem.name];
                }
              });
            }
          });
        });
        data.isInit = false;
      }, 0);
    });
  }
  /*let skus = [
  	[
  		"黑色",
  		"红色",
  		"白色"
  	],
  	[
  		"1PCS",
  		"2PCS"
  	]
  ]*/
  //笛卡尔乘积，计算规格
  // let cartesian = (arr) => {
  //   if (arr.length < 2) return arr[0] || [];
  //   return [].reduce.call(arr.item, function (col, set) {
  //     debugger;
  //     let res = [];
  //     col.forEach((c) => {
  //       set.forEach((s) => {
  //         let t = [].concat(Array.isArray(c) ? c : [c]);
  //         t.push(s);
  //         res.push(t);
  //       });
  //     });
  //     return res;
  //   });
  // };
  function cartesianAttribute(specifications: any, data: any = []) {
    const productSpecs = specifications.map((spec) => spec.item);
    const combinations = cartesianProduct(productSpecs);
    combinations.forEach((combination) => {
      console.log(combination);
      const specCombination = combination.map((spec) => spec.specName).join(' ');
      const item: any = {
        specName: specCombination,
      };
      data.push(item);
    });
    return data;
  }
  function cartesianProduct(arr) {
    return arr.reduce(
      (a, b) => {
        return a.flatMap((d) => {
          return b.map((e) => {
            return [...d, e];
          });
        });
      },
      [[]]
    );
  }
  // // 根据 attribute 进行排列组合，生成 skuData 数据
  // function combinationAttribute(index = 0, dataTemp = []) {
  //   if (index === 0) {
  //     for (let i = 0; i < props.attribute[0].item.length; i++) {
  //       const obj = {
  //         sku: props.attribute[0].item[i],
  //         [props.attribute[0].name]: props.attribute[0].item[i].name,
  //         specName: props.attribute[0].item[i].specName,
  //       };
  //       props.structure.forEach((v) => {
  //         // v.type == 'slot' &&
  //         if (!(v.skuProperty == false)) {
  //           // obj[v.name] = typeof v.defaultValue != 'undefined' ? v.defaultValue : '';
  //         }
  //       });
  //       dataTemp.push(obj);
  //     }
  //   } else {
  //     const temp = [];
  //     for (let i = 0; i < dataTemp.length; i++) {
  //       for (let j = 0; j < props.attribute[index].item.length; j++) {
  //         temp.push(JSON.parse(JSON.stringify(dataTemp[i])));
  //         temp[temp.length - 1][props.attribute[index].name] = props.attribute[index].item[j].name;
  //         temp[temp.length - 1]['sku'] = [{ ...temp[temp.length - 1]['sku'] }, { ...props.attribute[index].item[j] }]; // .join(props.separator);
  //         //  let specNames = obj.sku.map((o) => o.specName);
  //         temp[temp.length - 1]['specName'] = temp[temp.length - 1].sku.map((o) => o.specName).join(' ');
  //       }
  //     }
  //     dataTemp = temp;
  //   }
  //   if (index !== props.attribute.length - 1) {
  //     combinationAttribute(index + 1, dataTemp);
  //   } else {
  //     if (!data.isInit || props.async) {
  //       // 将原有的 sku 数据和新的 sku 数据比较，相同的 sku 则把原有的 sku 数据覆盖到新的 sku 数据里
  //       for (let i = 0; i < data.form.skuData.length; i++) {
  //         for (let j = 0; j < dataTemp.length; j++) {
  //           if (data.form.skuData[i].sku === dataTemp[j].sku) {
  //             dataTemp[j] = data.form.skuData[i];
  //           }
  //         }
  //       }
  //     }
  //     data.form.skuData = dataTemp;
  //   }
  // }

  function clearValidate() {
    skuFormRef.value.clearValidate();
  }

  //删除行
  const removeRow = async (row) => {
    const $table = skuTableRef.value;
    if ($table) {
      $table.remove(row);
      console.log('id:' + row.id);
      if (row.id) {
        let param = { id: row.id };
        //调用删除sku接口删除sku
        removeById(param);
      }
    }
  };

  //     },
  //   };
</script>

<style lang="less" scoped>
  .sku-container {
    :deep(.ant-card) {
      margin: 5px 0;
    }
    :deep(.ant-card .ant-card-head) {
      min-height: 30px;
      padding: 0 12px;
      border-right: 1px dotted #ebeef5;
    }
    :deep(.ant-card .ant-card-head .ant-card-head-title) {
      padding: 10px 0;
    }
    :deep(.ant-card-body) {
      padding: 12px 20px 10px;
      display: flex;
    }

    .sku-check {
      .theme-1 {
        margin-bottom: 10px;
        .item {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          &:last-child:nth-child(3n - 1) {
            margin-right: calc(100% - 32% * 2 - 4% / 2) !important;
          }
          .add-attr {
            width: 100%;
            margin-top: 10px;
          }
        }
      }
      .theme-2 {
        border: 1px solid #ebeef5;
        border-bottom: 0;
        margin-bottom: 20px;
      }
    }
    .sku-name {
      text-align: right;
    }
    .batch-set {
      width: 100%;
      margin-top: 5px;
    }
    .sku-list {
      line-height: initial;
      .required_title::before {
        content: '*';
        color: #f56c6c;
      }
    }
  }
</style>
